package com.qf.commons.core.listener;

import org.slf4j.MDC;
import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.event.GenericApplicationListener;
import org.springframework.core.Ordered;
import org.springframework.core.ResolvableType;
import org.springframework.core.env.ConfigurableEnvironment;

/**
 * 监听SpringBoot环境准备事件，进行相应的处理 - 设置MDC
 * author Ken
 * create_time 2022/8/16
 */
public class LogMDCHandlerListener implements GenericApplicationListener {


    @Override
    public boolean supportsEventType(ResolvableType eventType) {
        return eventType.isAssignableFrom(ApplicationEnvironmentPreparedEvent.class);
    }

    /**
     *
     * @param sourceType the event type (never {@code null}) - 代表当前发生的事件类型
     * @return
     *    如果返回true，表示当前事件类型是我这个类感兴趣的事件类型，就会触发onApplicationEvent方法，
     *    如果返回false，就表示该事件类型不感兴趣，onApplicationEvent就不会调用
     */
    @Override
    public boolean supportsSourceType(Class<?> sourceType) {
        return true;
    }

    /**
     * 事件处理方法
     * @param event the event to respond to
     */
    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        //强制转成 环境准备事件
        ApplicationEnvironmentPreparedEvent preparedEvent = (ApplicationEnvironmentPreparedEvent) event;
        //获得当前的环境
        ConfigurableEnvironment environment = preparedEvent.getEnvironment();
        //获得微服务名称
        String serviceName = environment.getProperty("spring.application.name");
        //设置MDC 即可
        MDC.put("filename", serviceName);
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE + 19;
    }
}
